function createPromise(callback){
    return new Promise((resolve,reject)=>{
        callback(resolve,reject)
    })
}

/**
 * 制作水印图片
 */
export default class MarkwaterMark{
    constructor(options){
        /* 初始化配置 */
       this.platform  = null 
       this.pixelRatio = null
       this.context = null
       this.options = options 
       this.ready = createPromise(this._init.bind(this))   
       /* 生成组件方法 */
       this.make = (cb) => { 
          if(this.context){
             this._markPicture(cb)
          }else{
              this.ready.then(()=>{
                 this.context && this._markPicture(cb)
              })
          }    
       }
    }
    /* 初始化方法 */
    _init(next,fail){
       const { platform , pixelRatio } = wx.getSystemInfoSync()
       this.platform = platform
       this.pixelRatio = pixelRatio
       const query = wx.createSelectorQuery()
       query.select('#' + this.options.id ).fields({
        node: true,
        size: true
      }).exec((res)=>{
        let {
            node,
        } = res[0] || {} 
        if (!node) return fail && fail()
        this.context = node.getContext('2d')    
        this.node = node
        next()
      })
    }
    /* 制作水印图片 */
    _markPicture(cb){
       const { width , height , bg ,color ,fontSize, fontFamily,fontWeight ,content , left, top ,rotate } = this.options
       this.node.width = (width || 200) * this.pixelRatio
       this.node.height =( height || 200) * this.pixelRatio
       this.context.scale(this.pixelRatio,this.pixelRatio)
       this.context.fillStyle = bg || '#fff'
       this.context.fillRect(0, 0, width, height)
       this.context.fillStyle = color || '#000'
       this.context.save()
       this.context.translate(left,top)
       this.context.rotate(Math.PI * rotate / 180 )
       this.context.font =  `${fontWeight} 400 ${fontSize} ${fontFamily}`
       this.context.fillText(content, 0, 0)
       this.context.restore() 
       this._savePicture(cb)
    }
    /* 生成图片 */
    _savePicture(cb){
     const { width , height  } = this.options
       wx.canvasToTempFilePath({
          x:0,
          y:0,
          width,
          height,
          destWidth:width*1,
          destHeight:height*1,
          canvas:this.node,
          success:function(res){
             cb && cb(res.tempFilePath)
          }
       })
    }
}
/**
 * 
 * @param {*} options 配置项
 */
function makeWatermark(options){
  if(!wx) return null
  return new MarkwaterMark(options) 
}

module.exports = makeWatermark
